Transaction management using Spring and Hibernate

Categories: Java; Tagged with: ; @ June 26th, 2012 22:07

Spring doesn’t directly manage transactions, it comes with a selection of transaction  managers, such as: DataSourceTransactionManager, HibernateTransactionManager, JpaTransactionManager etc,.

There are two way to manage transaction in Spring: based on programming or configuration. no matter which way we choose, we always need to define the beans needed:

Declaring transactions

Here we define a transactionManager using hibernateTransactionManager, and a transaction template:

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="globalRollbackOnParticipationFailure" value="false" />
      <property name="sessionFactory"  ref="sessionFactory" />
  </bean>
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
</bean>

‘sessionFactory’ bean configuration: http://liguoliang.com/2012/using-spring-jdbc-template/

And now, I’ll show you the the two  transaction management ways:

1. by Programming

	@Autowired
	private TransactionTemplate txTemplate;
	/**
	 * Insert new user using transactionTemplate.
	 * @param user
	 */
	public void insertUserByTxTemplate(final User user) {
		txTemplate.execute(new TransactionCallback() {

			@Override
			public Void doInTransaction(TransactionStatus txStatus) {
				try {
					Session session = sessionFactory.getCurrentSession();
					session.save(user);
					throw new RuntimeException("Exception throwed!");
				} catch (Exception e) {
					txStatus.setRollbackOnly();
				}
				return null;
			}
		});
	}

Manage transaction using txTemplate.execute().

2. by Configuration/Declaring

using annotation

	/**
	 * Insert new user using transaction manager.
	 * @param user
	 */
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=RuntimeException.class)
	public void insertUser(User user) {
		Session session = sessionFactory.getCurrentSession(); // SessionFactoryUtils.openSession(sessionFactory);
		user.setLogin_name(user.getName());
		session.save(user);
		// throw new RuntimeException("RunTimeException for Transaction testing...");
	}

If you are using STS(SpringSource tool suite) you can see there is an indicator:

image

About transaction rollback

  • by default: if there is a runtime exception (UnChecked exception), will rollback;
  • If rollback failed, check the @Transactional,  and the method:  if you get session by SessionFactoryUtils.openSession(sessionFactory),, rollback will failed – I think only sessionFactory.getCurrentSession() can work.

Links:

Spring Transaction – automatic rollback of previous db updates when one db update failes
Spring’s @Transactional does not rollback on checked exceptions
Transaction strategies: Understanding transaction pitfalls

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.